<!--
 * @Author: yongqing.cai
 * @Date: 2022-08-12
 -->
<template>
  <div v-show="modelIsOpen">
    <div class="modal-content">
      <div id="container"></div>
      <div class="input-card" style="width: 35rem">
        <div class="form-item">
          <span class="item-label">经纬度:</span>
          <div class="item-warp">
            <input class="item-input" id="lnglat" type="text" placeholder="例：121.484236,38.855603" />
            <div class="item-btn" id="regeo">转地址</div>
          </div>
        </div>
        <div class="form-item">
          <span class="item-label">地址:</span>
          <div class="item-warp">
            <input class="item-input" id="address" type="text" placeholder="例：北京火车站" />
            <div id="geo" class="item-btn">转经纬度</div>
          </div>
        </div>
        <div class="form-item">
          <span class="item-label">范围:</span>
          <div class="item-warp">
            <input class="item-input" id="distance" type="text" placeholder="例：300" />
            <div id="circle" class="item-btn">确认</div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="ilead-modal-footer">
      <button type="primary" icon="checkmark" @click="handleSubmit">提交</button>
      <button type="primary" ghost icon="close" @click="closeModal" style="margin-left: 10px">关闭</button>
    </div>
  </div>
</template>
<script>
import * as mapUtils from '@/utils/gdMap.js'

export default {
  data: function () {
    return {
      modelIsOpen: false
    }
  },
  watch: {
    modelIsOpen: function (val) {
      if (val) {
        this.initMap()
        document.getElementById('lnglat').value = ''
        document.getElementById('address').value = ''
        document.getElementById('distance').value = ''
      }
    }
  },
  created() {
    // this.initMap();
  },
  methods: {
    initMap() {
      let lng = 0,
        lat = 0
      var circle = null

      const that = this
      mapUtils.AMapGeocoder().then(() => {
        // eslint-disable-next-line no-undef
        var map = new AMap.Map('container', {
          resizeEnable: true,
          zoom: 17 // 级别
        })
        var options = {
          showButton: true, // 是否显示定位按钮
          position: 'LB', // 定位按钮的位置
          /* LT LB RT RB */
          offset: [10, 20], // 定位按钮距离对应角落的距离
          showMarker: true, // 是否显示定位点
          showCircle: false
        }
        // eslint-disable-next-line no-undef
        AMap.plugin(['AMap.Geolocation'], function () {
          // eslint-disable-next-line no-undef
          var geolocation = new AMap.Geolocation(options)
          map.addControl(geolocation)
          geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          })

          function onComplete(data) {
            // eslint-disable-next-line no-undef
            var geocoder = new AMap.Geocoder()
            // eslint-disable-next-line no-undef
            var marker = new AMap.Marker()

            function regeoCode() {
              var lnglat = document.getElementById('lnglat').value.split(',')
              console.log(lnglat)
              if (!lnglat) {
                that.$Message.error('请输入正确的经纬度')
                return
              }
              map.add(marker)
              marker.setPosition(lnglat)

              geocoder.getAddress(lnglat, function (status, result) {
                if (status === 'complete' && result.regeocode) {
                  var address = result.regeocode.formattedAddress
                  lng = lnglat[0]
                  lat = lnglat[1]
                  document.getElementById('address').value = address
                } else {
                  that.$Message.error('根据经纬度查询地址失败')
                }
              })
            }

            function geoCode() {
              var address = document.getElementById('address').value
              if (!address) {
                that.$Message.error('请输入正确的地址')
                return
              }
              geocoder.getLocation(address, function (status, result) {
                if (status === 'complete' && result.geocodes.length) {
                  var lnglat = result.geocodes[0].location
                  document.getElementById('lnglat').value =
                    lnglat.lng + ',' + lnglat.lat
                  lng = lnglat.lng
                  lat = lnglat.lat
                  marker.setPosition(lnglat)
                  map.add(marker)
                  map.setFitView(marker)
                } else {
                  that.$Message.error('根据地址查询位置失败')
                }
              })
            }

            function drawCircle() {
              console.log(circle)
              circle && map.remove(circle)

              mapUtils.AMapCircleEditor().then(() => {
                var radius = document.getElementById('distance').value
                if (!radius) {
                  that.$Message.error('请输入范围')
                  return
                }
                if (
                  typeof Number(radius) !== 'number' ||
                  Number(radius) === 'NaN'
                ) {
                  that.$Message.error('范围请输入数字')
                  return
                }
                console.log(radius)
                // eslint-disable-next-line no-undef
                circle = new AMap.Circle({
                  center: [lng, lat],
                  radius: Number(radius), // 半径
                  borderWeight: 3,
                  strokeColor: '#FF33FF',
                  strokeWeight: 6,
                  strokeOpacity: 0.2,
                  fillOpacity: 0.4,
                  strokeStyle: 'dashed',
                  strokeDasharray: [10, 10],
                  // 线样式还支持 'dashed'
                  fillColor: '#1791fc',
                  zIndex: 50
                })

                map.add(circle)
                // 缩放地图到合适的视野级别
                map.setFitView([circle])
              })
            }

            console.log(data)
            lat = data.position.lat
            lng = data.position.lng
            document.getElementById('lnglat').value = lng + ',' + lat
            if (lng && lat) {
              regeoCode()
            }

            map.on('click', function (e) {
              console.log(e)
              lng = e.lnglat.lng
              lat = e.lnglat.lat
              document.getElementById('lnglat').value = lng + ',' + lat
              regeoCode()
            })

            document.getElementById('regeo').onclick = regeoCode
            document.getElementById('geo').onclick = geoCode
            document.getElementById('circle').onclick = drawCircle
            document.getElementById('lnglat').onkeydown = function (e) {
              if (e.keyCode === 13) {
                regeoCode()
                return false
              }
              return true
            }
          }

          function onError(data) {
            console.error('定位失败', data)
            that.$Message.error('定位失败,请刷新网页')
          }
        })
      })
    },
    initMap2() {
      let lng = 0,
        lat = 0
      var circle = null

      const that = this
      mapUtils.AMapGeocoder().then(() => {
        AMap.plugin('AMap.Geolocation', function () {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量
            offset: [10, 20],
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            position: 'RB'
          })

          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          })

          function onComplete(data) {
            console.log(data)
            lat = data.position.lat
            lng = data.position.lng

            var map = new AMap.Map('container', {
              resizeEnable: true,
              zoom: 17, // 级别
              center: [lng, lat]
            })

            var geocoder = new AMap.Geocoder()
            var marker = new AMap.Marker()
            function regeoCode() {
              var lnglat = document.getElementById('lnglat').value.split(',')
              if (!lnglat) {
                that.$Message.error('请输入正确的经纬度')
                return
              }
              map.add(marker)
              marker.setPosition(lnglat)

              geocoder.getAddress(lnglat, function (status, result) {
                if (status === 'complete' && result.regeocode) {
                  var address = result.regeocode.formattedAddress
                  lng = lnglat[0]
                  lat = lnglat[1]
                  document.getElementById('address').value = address
                } else {
                  that.$Message.error('根据经纬度查询地址失败')
                }
              })
            }

            function geoCode() {
              var address = document.getElementById('address').value
              if (!address) {
                that.$Message.error('请输入正确的地址')
                return
              }
              geocoder.getLocation(address, function (status, result) {
                if (status === 'complete' && result.geocodes.length) {
                  var lnglat = result.geocodes[0].location
                  document.getElementById('lnglat').value =
                    lnglat.lng + ',' + lnglat.lat
                  lng = lnglat.lng
                  lat = lnglat.lat
                  marker.setPosition(lnglat)
                  map.add(marker)
                  map.setFitView(marker)
                } else {
                  that.$Message.error('根据地址查询位置失败')
                }
              })
            }

            map.on('click', function (e) {
              console.log(e)
              document.getElementById('lnglat').value =
                e.lnglat.lng + ',' + e.lnglat.lat
              lng = e.lnglat.lng
              lat = e.lnglat.lat
              regeoCode()
            })

            document.getElementById('regeo').onclick = regeoCode
            document.getElementById('geo').onclick = geoCode
            document.getElementById('circle').onclick = drawCircle
            document.getElementById('lnglat').onkeydown = function (e) {
              if (e.keyCode === 13) {
                regeoCode()
                return false
              }
              return true
            }

            function drawCircle() {
              console.log(circle)
              circle && map.remove(circle)

              mapUtils.AMapCircleEditor().then(() => {
                var radius = document.getElementById('distance').value
                if (!radius) {
                  that.$Message.error('请输入范围')
                  return
                }
                if (
                  typeof Number(radius) !== 'number' ||
                  Number(radius) === 'NaN'
                ) {
                  that.$Message.error('范围请输入数字')
                  return
                }
                console.log(radius)
                circle = new AMap.Circle({
                  center: [lng, lat],
                  radius: Number(radius), // 半径
                  borderWeight: 3,
                  strokeColor: '#FF33FF',
                  strokeOpacity: 1,
                  strokeWeight: 6,
                  strokeOpacity: 0.2,
                  fillOpacity: 0.4,
                  strokeStyle: 'dashed',
                  strokeDasharray: [10, 10],
                  // 线样式还支持 'dashed'
                  fillColor: '#1791fc',
                  zIndex: 50
                })

                map.add(circle)
                // 缩放地图到合适的视野级别
                map.setFitView([circle])
              })
            }
          }

          function onError(data) {
            console.error('定位失败', data)
            that.$Message.error('定位失败,请刷新网页')
          }
        })
      })
    },
    reset: function () { },

    closeModal: function () {
      this.modelIsOpen = false
    },

    handleSubmit: function () {
      let lnglat = document.getElementById('lnglat').value.split(',')
      let address = document.getElementById('address').value
      let distance = document.getElementById('distance').value
      if (this.isEmpty(lnglat)) {
        this.$Message.error('经纬度不能为空')
        return
      }
      if (this.isEmpty(address)) {
        this.$Message.error('地址不能为空')
        return
      }
      if (this.isEmpty(distance)) {
        this.$Message.error('距离不能为空')
        return
      }
      let model = {
        lng: lnglat[0],
        lat: lnglat[1],
        address: address,
        distance: distance
      }
      this.$emit('getAddressInfo', model)
      this.modelIsOpen = false
    },

    isEmpty(value) {
      return value === '' || value === undefined || value === null
    }
  }
}
</script>
<style lang="scss">
.modal-content {
  position: relative;

  #container {
    width: 100%;
    height: 700px;
  }

  .input-card {
    position: absolute;
    top: 1rem;
    bottom: revert-layer;
    width: 28rem;
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border-radius: 0.25rem;
    width: 22rem;
    border-width: 0;
    border-radius: 0.4rem;
    box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
    right: 1rem;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 0.75rem 1.25rem;

    .form-item {
      display: flex;
      align-items: center;
      margin-top: 0.5rem;

      .item-label {
        width: 4rem;
        text-align: right;
      }

      .item-warp {
        flex: 1;
        display: flex;
        margin-left: 1rem;
        justify-content: space-between;
        align-items: center;

        .item-input {
          flex: 1;
          width: 100%;
          line-height: 1.5;
          padding: 0.25rem;
          color: #495057;
          border: 1px solid #ced4da;
          border-radius: 0.25rem;
          -webkit-appearance: none;
          -moz-appearance: none;
          appearance: none;
        }

        .item-input:focus {
          border-color: #80bdff;
          outline: 0;
          box-shadow: 0 0 0 0.1rem rgba(128, 189, 255, 0.1);
        }

        .item-btn {
          width: 6rem;
          margin-left: 1rem;
          border: 1px solid #ced4da;
          color: #495057;
          padding: 0.25rem;
          text-align: center;
          border-radius: 0.25rem;
          cursor: pointer;
          user-select: none;
        }

        .item-btn:hover {
          text-decoration: none;
          color: #fff;
          background-color: #25a5f7;
          border-color: #25a5f7;
        }
      }
    }
  }
}
</style>
